from django.shortcuts import render, redirect
from django.conf import settings
import requests
from urllib.parse import quote
from django.http import HttpResponse, HttpResponseRedirect
from django.contrib.auth import logout
from django.http import JsonResponse
from .models import User
from django.contrib.auth import login
from django.utils import timezone
from django.shortcuts import render
from django.contrib.auth.decorators import login_required

def index(request):
    return render(request, 'index.html')

def user_login(request):
    next_url = request.GET.get('next', '/')  
    appid = settings.WECHAT_APPID
    print(appid)
    redirect_uri = quote(settings.WECHAT_REDIRECT_URI)
    url = f"https://open.weixin.qq.com/connect/qrconnect?appid={appid}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_login&state={next_url}#wechat_redirect"
    return HttpResponseRedirect(url)


def logout_view(request):
    logout(request)
    # 重定向到登录页面或者主页
    return redirect('index')


def wechat_callback(request):
    code = request.GET.get('code')
    state = request.GET.get('state', '/')

    # 利用code获取access_token
    appid = settings.WECHAT_APPID
    secret = settings.WECHAT_SECRET
    url = f'https://api.weixin.qq.com/sns/oauth2/access_token?appid={appid}&secret={secret}&code={code}&grant_type=authorization_code'
    response = requests.get(url)
    data = response.json()

    access_token = data.get('access_token')
    openid = data.get('openid')
    url = f'https://api.weixin.qq.com/sns/userinfo?access_token={access_token}&openid={openid}'
    response = requests.get(url)

    response.encoding = 'utf-8'  # 设置响应内容的编码为UTF-8
    user_info = response.json()

    # 创建或者更新用户信息
    user = User.create_or_update_from_wechat(user_info)
    # 更新 last_login 字段
    user.last_login = timezone.now()
    user.save(update_fields=['last_login'])
    
    # 选择要登录的后端认证系统，这里可以选择Django自带的，也可以选择微信的
    backend = 'django.contrib.auth.backends.ModelBackend'
    # backend = 'allauth.account.auth_backends.AuthenticationBackend'
    user.backend = backend  # 设置用户实例的后端属性
    login(request, user, backend=backend)  # 登录用户，传入backend参数
    
    # 这里我随便写了一个url名称
    return redirect(state)
